<template>
  <div class="following-tab">
    <el-card class="following-header">
      <div class="header-content">
        <div class="following-info">
          <h3>关注管理</h3>
          <p>管理您的关注和粉丝</p>
        </div>
        <el-button @click="findFriends">
          <el-icon><Search /></el-icon>
          发现好友
        </el-button>
      </div>
    </el-card>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ followingCount }}</div>
            <div class="stat-label">关注</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ followersCount }}</div>
            <div class="stat-label">粉丝</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ mutualCount }}</div>
            <div class="stat-label">互关</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 标签切换 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="我的关注" name="following">
        <div class="user-list" v-loading="loading">
          <div v-if="followingList.length === 0" class="empty-state">
            <el-empty description="您还没有关注任何人">
              <el-button type="primary" @click="findFriends">
                去发现好友
              </el-button>
            </el-empty>
          </div>

          <div v-else class="users-grid">
            <div 
              v-for="user in followingList" 
              :key="user.id"
              class="user-card"
            >
              <el-card shadow="hover">
                <div class="user-info">
                  <img 
                    :src="user.avatar || '/placeholder-avatar.png'" 
                    :alt="user.username"
                    class="user-avatar"
                  />
                  <div class="user-details">
                    <h4 class="username">{{ user.username }}</h4>
                    <p class="user-bio">{{ user.bio || '这个人很懒，什么都没写' }}</p>
                    <div class="user-stats">
                      <span>{{ user.outfits_count || 0 }} 搭配</span>
                      <span>{{ user.followers_count || 0 }} 粉丝</span>
                    </div>
                  </div>
                </div>
                
                <div class="user-actions">
                  <el-button size="small" @click="viewProfile(user)">
                    查看主页
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="unfollowUser(user)"
                  >
                    取消关注
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="我的粉丝" name="followers">
        <div class="user-list" v-loading="loading">
          <div v-if="followersList.length === 0" class="empty-state">
            <el-empty description="您还没有粉丝" />
          </div>

          <div v-else class="users-grid">
            <div 
              v-for="user in followersList" 
              :key="user.id"
              class="user-card"
            >
              <el-card shadow="hover">
                <div class="user-info">
                  <img 
                    :src="user.avatar || '/placeholder-avatar.png'" 
                    :alt="user.username"
                    class="user-avatar"
                  />
                  <div class="user-details">
                    <h4 class="username">{{ user.username }}</h4>
                    <p class="user-bio">{{ user.bio || '这个人很懒，什么都没写' }}</p>
                    <div class="user-stats">
                      <span>{{ user.outfits_count || 0 }} 搭配</span>
                      <span>{{ user.following_count || 0 }} 关注</span>
                    </div>
                  </div>
                </div>
                
                <div class="user-actions">
                  <el-button size="small" @click="viewProfile(user)">
                    查看主页
                  </el-button>
                  <el-button 
                    v-if="!user.isFollowing"
                    size="small" 
                    type="primary" 
                    @click="followUser(user)"
                  >
                    回关
                  </el-button>
                  <el-button 
                    v-else
                    size="small" 
                    @click="unfollowUser(user)"
                  >
                    已关注
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="推荐关注" name="recommendations">
        <div class="user-list" v-loading="loading">
          <div v-if="recommendationsList.length === 0" class="empty-state">
            <el-empty description="暂无推荐用户" />
          </div>

          <div v-else class="users-grid">
            <div 
              v-for="user in recommendationsList" 
              :key="user.id"
              class="user-card"
            >
              <el-card shadow="hover">
                <div class="user-info">
                  <img 
                    :src="user.avatar || '/placeholder-avatar.png'" 
                    :alt="user.username"
                    class="user-avatar"
                  />
                  <div class="user-details">
                    <h4 class="username">{{ user.username }}</h4>
                    <p class="user-bio">{{ user.bio || '这个人很懒，什么都没写' }}</p>
                    <div class="user-stats">
                      <span>{{ user.outfits_count || 0 }} 搭配</span>
                      <span>{{ user.followers_count || 0 }} 粉丝</span>
                    </div>
                    <div class="recommendation-reason" v-if="user.reason">
                      <el-tag size="small" type="info">{{ user.reason }}</el-tag>
                    </div>
                  </div>
                </div>
                
                <div class="user-actions">
                  <el-button size="small" @click="viewProfile(user)">
                    查看主页
                  </el-button>
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click="followUser(user)"
                  >
                    关注
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { socialAPI } from '@/api'

const loading = ref(false)
const activeTab = ref('following')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 统计数据
const followingCount = ref(0)
const followersCount = ref(0)
const mutualCount = ref(0)

// 用户列表
const followingList = ref([])
const followersList = ref([])
const recommendationsList = ref([])

const loadData = async () => {
  try {
    loading.value = true
    
    if (activeTab.value === 'following') {
      await loadFollowing()
    } else if (activeTab.value === 'followers') {
      await loadFollowers()
    } else if (activeTab.value === 'recommendations') {
      await loadRecommendations()
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadFollowing = async () => {
  try {
    const response = await socialAPI.getFollowing({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (response.code === 200) {
      followingList.value = response.data.list || []
      total.value = response.data.total || 0
      followingCount.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取关注列表失败:', error)
  }
}

const loadFollowers = async () => {
  try {
    const response = await socialAPI.getFollowers({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    if (response.code === 200) {
      followersList.value = response.data.list || []
      total.value = response.data.total || 0
      followersCount.value = response.data.total || 0
    }
  } catch (error) {
    console.error('获取粉丝列表失败:', error)
  }
}

const loadRecommendations = async () => {
  try {
    const response = await socialAPI.getFriendRecommendations()
    
    if (response.code === 200) {
      recommendationsList.value = response.data || []
      total.value = response.data.length || 0
    }
  } catch (error) {
    console.error('获取推荐列表失败:', error)
  }
}

const handleTabChange = (tabName) => {
  activeTab.value = tabName
  currentPage.value = 1
  loadData()
}

const followUser = async (user) => {
  try {
    const response = await socialAPI.followUser(user.id)
    
    if (response.code === 200) {
      user.isFollowing = true
      ElMessage.success('关注成功')
      
      // 更新统计数据
      followingCount.value++
    }
  } catch (error) {
    console.error('关注失败:', error)
    ElMessage.error('关注失败')
  }
}

const unfollowUser = async (user) => {
  try {
    await ElMessageBox.confirm(`确定要取消关注 ${user.username} 吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await socialAPI.followUser(user.id)
    
    if (response.code === 200) {
      user.isFollowing = false
      ElMessage.success('已取消关注')
      
      // 更新统计数据
      followingCount.value--
      
      // 如果在关注列表页面，移除该用户
      if (activeTab.value === 'following') {
        followingList.value = followingList.value.filter(u => u.id !== user.id)
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消关注失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const viewProfile = (user) => {
  // 跳转到用户主页
  console.log('查看用户主页:', user)
}

const findFriends = () => {
  // 跳转到发现页面
  console.log('跳转到发现页面')
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.following-tab {
  space-y: 20px;
}

.following-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.following-info h3 {
  margin: 0 0 4px 0;
  color: #333;
}

.following-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.user-list {
  margin-top: 20px;
}

.users-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.user-card {
  width: 100%;
}

.user-info {
  display: flex;
  margin-bottom: 16px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 16px;
}

.user-details {
  flex: 1;
}

.username {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: 600;
}

.user-bio {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.user-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.recommendation-reason {
  margin-top: 8px;
}

.user-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-wrapper {
  margin-top: 40px;
  text-align: center;
}

@media (max-width: 768px) {
  .users-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
  }
  
  .user-avatar {
    margin: 0 auto 12px auto;
  }
  
  .user-actions {
    flex-direction: column;
  }
}
</style>
